package com.webapp.helper;

import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.List;

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@SuppressWarnings("deprecation")
public class HttpUtils {

	private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);   
	
	
	 public static void postFile(String url, String apikey,byte[] b) {
		 try {
			 HttpClient httpClient = HttpClients.createDefault();
			 HttpPost httppost = new HttpPost(url);
			 httppost.addHeader("apikey",apikey);
			 MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();
			 mEntityBuilder.addBinaryBody(new Date().getTime()+".bin", b);
			 httppost.setEntity(mEntityBuilder.build());
			 httpClient.execute(httppost);
			} catch (Exception e) {
				logger.error("e:{}",e);
			}
	    }
	
	 
		@SuppressWarnings("resource")
		public static String postJsonWithHeader(String url, String json, String header) {
			logger.warn("HttpUtils.postJson[info:\n{},\n{},header:\n{}\n]",url,json,header);
			String result = "500";
	        HttpPost post = new HttpPost(url);
	        post.addHeader("Content-type","application/json;charset=utf-8");
	        post.addHeader("Accept", "*/*");
	        post.addHeader("Authorization",header);
	        post.setEntity(new StringEntity(json, Charset.forName("UTF-8")));
	        try {
	        	DefaultHttpClient httpClient = new DefaultHttpClient();
	        	HttpResponse response = httpClient.execute(post);
				result = EntityUtils.toString(response.getEntity(),"UTF-8");
				logger.warn("HttpUtils.postJson[res:{}]",result);
			} catch (ParseException e) {
				logger.error("HttpUtils.postJson[ParseException.error:{}]",e);
			} catch (IOException e) {
				logger.error("HttpUtils.postJson[IOException.error:{}]",e);
			}
	        return result;
		}
	 /**
     * 标准post
     * @param url
     * @param param
     * @return
     */
    public static String sendPost(String url, String param) {
    	logger.warn("HttpUtils.sendPost url:{},param:{}"+url+param);
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            logger.warn("HttpUtils.sendPost result:{}"+result);
        } catch (Exception e) {
        	logger.warn("[HttpUtils.sendPost data:{},error:{}]"+param + url+ e);
            e.printStackTrace();
        }
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

	
	 /**
     * http get
     * @param url
     * @return
     */
    @SuppressWarnings({ "resource"})
	public static String get(String url){
        String result = "500";
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
		try {
			HttpResponse response = httpClient.execute(get);
			result = EntityUtils.toString(response.getEntity(),"UTF-8");
		} catch (ParseException e) {
			logger.error("HttpUtils.get[ParseException.error:{}]",e);
		} catch (IOException e) {
			logger.error("HttpUtils.get[IOException.error:{}]",e);
		}
		return result;
    }
    
  	/**
  	 * post发送http请求
  	 * @param url
  	 * @return
  	 */
      @SuppressWarnings("resource")
  	public static String postSun(String url,String token){
          String result = "500";
          DefaultHttpClient httpClient = new DefaultHttpClient();
          HttpPost post = new HttpPost(url);
          post.addHeader("token",token);
  		try {
  			HttpResponse response = httpClient.execute(post);
  			result = EntityUtils.toString(response.getEntity(),"UTF-8");
  		} catch (ParseException e) {
  			logger.error("HttpUtils.postParams[ParseException.error:{}]",e);
  		} catch (IOException e) {
  			logger.error("HttpUtils.postParams[IOException.error:{}]",e);
  		}
  		return result;
      }
      
    
	
    @SuppressWarnings("resource")
	public static String postJson(String url,String jsonStr){
		logger.warn("HttpUtils.postJson[info:{},{}]",url,jsonStr);
		String result = "500";
        HttpPost post = new HttpPost(url);
        post.addHeader("Content-type","application/json;charset=utf-8");
        post.setHeader("Accept", "*/*");
        post.setEntity(new StringEntity(jsonStr, Charset.forName("UTF-8")));
        try {
        	DefaultHttpClient httpClient = new DefaultHttpClient();
        	HttpResponse response = httpClient.execute(post);
			result = EntityUtils.toString(response.getEntity(),"UTF-8");
			logger.warn("HttpUtils.postJson[res:{}]",result);
		} catch (ParseException e) {
			logger.error("HttpUtils.postJson[ParseException.error:{}]",e);
		} catch (IOException e) {
			logger.error("HttpUtils.postJson[IOException.error:{}]",e);
		}
        return result;
	}
	public static String postWxJson(String url,String jsonStr,String header) throws URISyntaxException {
		HttpClient httpClient = new DefaultHttpClient();
      	logger.warn("HttpUtils.postJson[info:{},{}]",url,jsonStr);
		String result = "500";
		HttpPost post = new HttpPost(url);
		post.addHeader("Content-type","application/json;charset=utf-8");
		post.setHeader("Accept", "*/*");
		post.setHeader("Authorization", header);
		post.setEntity(new StringEntity(jsonStr, Charset.forName("UTF-8")));
		try {
			HttpResponse response = httpClient.execute(post);
			result = EntityUtils.toString(response.getEntity(),"UTF-8");
			logger.warn("HttpUtils.postJson[res:{}]",result);
		} catch (ParseException e) {
			logger.error("HttpUtils.postJson[ParseException.error:{}]",e);
		} catch (IOException e) {
			logger.error("HttpUtils.postJson[IOException.error:{}]",e);
		}
		return result;
	}

}
